package com.liuzhilin.controller;

import com.fasterxml.jackson.core.JsonParser;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.liuzhilin.service.UserService;
import com.liuzhilin.util.Response;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/userAppeal")
public class UserAppeal extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        Response.setCorsHeaders(response);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();


        // 从前端请求体中获取数据
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String body = sb.toString();

        // 将JSON字符串转换为Java对象
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(body, JsonObject.class);
        String username = jsonObject.get("username").getAsString();
        String appealTarget = jsonObject.get("appealTarget").getAsString();
        String content = jsonObject.get("content").getAsString();

        //这里应该是将申诉信息存储到数据库的代码
        boolean success = UserService.saveAppealToDatabase(username, appealTarget, content);

        if (success) {
            response.setStatus(HttpServletResponse.SC_OK);
            out.print("{\"message\":\"申诉成功，请耐心等待！\"}");
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.print("{\"message\":\"申诉失败，请稍后再试\"}");
        }
    }

    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response) {
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }

}
